<template>
  <div class="app-container">
    <!-- 面包屑导航 -->
    <el-breadcrumb separator-class="el-icon-arrow-right" style="margin-bottom: 20px;">
      <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item :to="{ path: '/picture/list' }">相册列表</el-breadcrumb-item>
      <el-breadcrumb-item>照片管理</el-breadcrumb-item>
    </el-breadcrumb>

    <el-card class="main-card">
      <!-- 标题 -->
      <div class="title">{{ '照片管理' }}</div>
      <!-- 相册信息 -->
      <div class="album-info">
        <el-image fit="cover" class="album-cover" :src="albumInfo.cover" />
        <div class="album-detail">
          <div style="margin-bottom:0.6rem">
            <span class="album-name">{{ albumInfo.name }}</span>
            <span class="photo-count">当前:<b>{{ albumInfo.pictureCount }}</b>张</span>
            <span class="photo-count">总容量:<b>{{ albumInfo.size }}</b>张</span>
            <span class="photo-count">剩余:<b>{{ albumInfo.surplus }}</b>张</span>
          </div>
          <div>
          <span v-if="albumInfo.description" class="album-desc">
            {{ albumInfo.description }}
          </span>
            <el-button icon="el-icon-picture" type="primary" size="small" @click="uploadPhoto = true">上传照片</el-button>
          </div>
        </div>
        <!-- 相册操作 -->
        <div class="operation">
          <div class="all-check">
            <!-- <el-checkbox :indeterminate="isIndeterminate" v-model="checkAll" @change="handleCheckAllChange">
              全选
            </el-checkbox> -->
            <div class="check-count">已选择{{ selectPhotoIdList.length }}张</div>
          </div>
          <el-button
            type="success"
            @click="movePictureToOtherAlbum"
            :disabled="selectPhotoIdList.length === 0"
            size="small"
            icon="el-icon-deleteItem"
          >
            移动到
          </el-button>
          <el-button
            type="danger"
            @click="batchDelete"
            :disabled="selectPhotoIdList.length === 0"
            size="small"
            icon="el-icon-deleteItem"
          >
            批量删除
          </el-button>
        </div>
      </div>
      <!-- 照片列表 -->
      <el-row class="photo-container" :gutter="10">
        <!-- 空状态 -->
        <el-empty v-if="photoList.length === 0" description="暂无照片" />
        <el-checkbox-group v-model="selectPhotoIdList" @change="handleCheckedPhotoChange">
          <el-col :md="4" v-for="item of photoList" :key="item.id">
            <el-checkbox :label="item.id">
              <div class="photo-item">
                <!-- 照片操作 -->
                <div class="photo-opreation">
                  <el-dropdown @command="handleCommand">
                    <i class="el-icon-more" style="color:#fff" />
                    <el-dropdown-menu slot="dropdown">
                      <el-dropdown-item :command="'delete' + item.id">
                        <i class="el-icon-delete" />删除
                      </el-dropdown-item>
                    </el-dropdown-menu>
                  </el-dropdown>
                </div>
                <el-image style="width: 195px; height: 105px;" fit="cover" class="photo-img" :src="item.url" :preview-photoSrc-list="[item.url]"/>
              </div>
            </el-checkbox>
          </el-col>
        </el-checkbox-group>
      </el-row>
      <!-- 分页 -->
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="query.current"
        :page-sizes="[50, 80]"
        :page-size="query.size"
        layout="total, sizes, prev, pager, next, jumper"
        :total="query.total">
      </el-pagination>
      <!-- 上传模态框 -->
      <el-dialog :visible.sync="uploadPhoto" width="20%" >
        <div class="dialog-title-container" slot="title">
          上传照片
        </div>
        <!-- 上传 -->
        <div class="upload-container">
          <el-upload
            drag
            class="upload-demo"
            action=""
            :on-preview="handlePreview"
            :http-request="uploadMainImg"
            :on-remove="handleRemove"
            :file-list="uploadList"
            list-type="picture">
            <i class="el-icon-upload"></i>
            <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
            <div slot="tip" class="el-upload__tip">只能上传jpg/png文件，且不超过500kb</div>
          </el-upload>
        </div>
        <div slot="footer">
          <div class="upload-footer">
            <div class="upload-count">共上传{{ uploadList.length }}张照片</div>
            <div style="margin-left:auto">
              <el-button @click="closeUpload">取 消</el-button>
              <el-button @click="savePhotos" type="primary" :disabled="uploadList.length === 0">
                提交
              </el-button>
            </div>
          </div>
        </div>
      </el-dialog>
      <!-- 编辑对话框 -->
      <el-dialog :visible.sync="editPhoto" width="30%">
        <div class="dialog-title-container" slot="title">
          修改信息
        </div>
        <el-form label-width="80px" size="medium" :model="photoForm">
          <el-form-item label="照片名称">
            <el-input style="width:220px" v-model="photoForm.photoName" />
          </el-form-item>
          <el-form-item label="照片描述">
            <el-input style="width:220px" v-model="photoForm.photoDesc" />
          </el-form-item>
        </el-form>
        <div slot="footer">
          <el-button @click="editPhoto = false">取 消</el-button>
          <el-button type="primary" @click="updatePhoto">
            确 定
          </el-button>
        </div>
      </el-dialog>
      <!-- 移动对话框 -->
      <el-dialog :visible.sync="movePhoto" width="30%">
        <div class="dialog-title-container" slot="title">
          移动照片
        </div>
        <el-empty v-if="albumList.length < 2" description="暂无其他相册" />
        <el-form v-else label-width="80px" size="medium" :model="photoForm">
          <el-radio-group v-model="albumId">
            <div class="album-check-item">
              <template v-for="item of albumList">
                <el-radio
                  v-if="item.id !== albumInfo.id"
                  :key="item.id"
                  :label="item.id"
                  style="margin-bottom:1rem"
                >
                  <div class="album-check">
                    <el-image
                      fit="cover"
                      class="album-check-cover"
                      :src="item.cover"
                    />
                    <div style="margin-left:0.5rem">{{ item.name }}</div>
                  </div>
                </el-radio>
              </template>
            </div>
          </el-radio-group>
        </el-form>
        <div slot="footer">
          <el-button @click="closeMovePhoto">取 消</el-button>
          <el-button
            :disabled="albumId == null"
            type="primary"
            @click="updatePhotoAlbum">
            确 定
          </el-button>
        </div>
      </el-dialog>
    </el-card>
  </div>


</template>

<script>
import * as imageConversion from "image-conversion";
import albumApi from '../../api/album';
import fileApi from "@/api/file";
export default {
  created() {
    // 相册id
    this.id = this.$route.params.id;
    this.fetchAlbumInfo();
    this.fetchAllPicture();
  },
  data: function() {
    return {
      id: null,
      loading: true,
      checkAll: false,
      isIndeterminate: false,
      uploadPhoto: false,
      editPhoto: false,
      movePhoto: false,
      batchDeletePhoto: false,
      uploadList: [],
      photoList: [],
      photoIdList: [],
      selectPhotoIdList: [],
      albumList: [],
      albumInfo: {
        id: null,
        name: "",
        description: "",
        cover: "",
        pictureCount: 0,
        size: 0,
        surplus: 0
      },
      ids: [],
      photoForm: {
        id: null,
        photoName: "",
        photoDesc: ""
      },
      albumId: null,
      current: 1,
      size: 18,
      count: 0,
      query: {
        current: 1,
        size: 50,
        total: 0,
        albumId: this.$route.params.id
      }
    };
  },
  methods: {
    // 移动照片到其他相册
    movePictureToOtherAlbum() {
      this.movePhoto = true;
      this.fetchAlbumList();
    },

    // 获取相册列表
    fetchAlbumList() {
      albumApi.getAlbumList(this.id).then(response => {
        if (response.code === 200) {
          this.albumList = response.data;
        }
      })
    },

    // 获取相册详情信息
    fetchAlbumInfo() {
      albumApi.info(this.id).then(response => {
        if (response.code === 200) {
          this.albumInfo = response.data;
        }
      })
    },

    // 关闭移动相册的弹框
    closeMovePhoto() {
      this.movePhoto = false;
      this.albumId = '';
    },

    fetchAllPicture() {
      albumApi.getAllPicture(this.query).then(response => {
        if (response.code === 200) {
          this.photoList = response.data.pictureList;
          this.query.total = response.data.total;
        }
      })
    },

    // val 是切换之后的每页显示多少条
    handleSizeChange(val) {
      this.query.size = val;
      this.fetchAllPicture();
    },
    // 当页码改变后触发此方法 val是当前点击（或输入）的页码
    handleCurrentChange(val) {
      this.query.current = val;
      this.fetchAllPicture();
    },

    closeUpload() {
      this.uploadPhoto = false;
      this.uploadList = [];
    },

    handlePreview(file) {
      console.log(file);
    },

    uploadMainImg(file) {
      const data = new FormData();
      data.append('file', file.file);
      fileApi.uploadImage(data).then(response => {
        if(response.code === 200) {
          //this.albumForum.cover = response.data;
          this.uploadList.push(response.data);
        } else if (response.code === 306) {
          this.$notify.error({
            title: '错误',
            message: '您没有上传文件权限，请联系管理员',
            duration: 1500
          });
        } else {
          this.$notify.error({
            title: '错误',
            message: '系统异常，请稍后再试',
            duration: 1500
          });
        }
      }).catch(err => {
        this.$message({
          type: 'error',
          message: '上传失败'
        })
      })
    },

    sizeChange(size) {
      this.size = size;
    },
    currentChange(current) {
      this.current = current;
    },

    batchDelete() {
      this.$confirm('确认删除这些记录吗?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        // 发送删除请求
        const data = {ids: this.ids}
        albumApi.batchDeletePicture(data).then(response => {
          if (response.code === 200) {
            this.$notify({
              title: '成功',
              message: '删除成功',
              type: 'success',
              duration: 1500
            });
          } else if (response.code === 306) {
            this.$notify.error({
              title: '错误',
              message: '您没有操作权限，请联系管理员',
              duration: 1500
            });
          } else {
            this.$notify.error({
              title: '错误',
              message: '系统异常，请稍后再试',
              duration: 1500
            });

          }
          // 刷新列表
          this.fetchAllPicture();
          this.fetchAlbumInfo();
        })
      }).catch(() => {
        // 取消删除
      });
    },

    savePhotos() {
      const data = {
        albumId: this.id,
        urlList: this.uploadList
      }
      albumApi.savePicture(data).then(response => {
        if (response.code === 200) {
          this.$notify({
            title: '成功',
            message: '提交成功',
            type: 'success',
            duration: 1500
          });
        } else if (response.code === 306) {
          this.$notify.error({
            title: '错误',
            message: '您没有上传文件权限，请联系管理员',
            duration: 1500
          });
        } else if (response.code === 15009) {
          this.$notify.error({
            title: '错误',
            message: '相册容量超出上限',
            duration: 1500
          });
        } else {
          this.$notify.error({
            title: '错误',
            message: '系统异常，请稍后再试',
            duration: 1500
          });
        }
        this.closeUpload();
        this.fetchAllPicture();
        this.fetchAlbumInfo();
      })
    },
    updatePhoto() {

    },

    // 移动照片到其他相册
    updatePhotoAlbum() {
      console.log('选中的相册id=', this.albumId);
      const data = {
        albumId: this.albumId,
        pictureIds: this.ids
      }

      albumApi.movePicture(data).then(response => {
        if (response.code === 200) {
          this.$notify({
            title: '成功',
            message: '移动成功',
            type: 'success',
            duration: 1500
          });
        } else if (response.code === 306) {
          this.$notify.error({
            title: '错误',
            message: '您没有操作权限，请联系管理员',
            duration: 1500
          });
        } else {
          this.$notify.error({
            title: '错误',
            message: '系统异常，请稍后再试',
            duration: 1500
          });
        }
        // 刷新列表
        this.closeMovePhoto();
        this.fetchAllPicture();
        this.fetchAlbumInfo();
      })
    },

    handleRemove(file) {

    },
    upload(response) {
      // this.uploadList.push({ url: response.data });
    },
    beforeUpload(file) {
      return new Promise(resolve => {
        if (file.size / 1024 < this.config.UPLOAD_SIZE) {
          resolve(file);
        }
        // 压缩到200KB,这里的200就是要压缩的大小,可自定义
        imageConversion
          .compressAccurately(file, this.config.UPLOAD_SIZE)
          .then(res => {
            resolve(res);
          });
      });
    },

    handleCheckAllChange(val) {
      console.log('val=', val)
      this.selectPhotoIdList = val ? this.photoIdList : [];
      this.isIndeterminate = false;
    },

    handleCheckedPhotoChange(value) {
      let checkedCount = value.length;
      this.checkAll = checkedCount === this.photoIdList.length;
      this.isIndeterminate =
        checkedCount > 0 && checkedCount < this.photoIdList.length;
      console.log("value=", value)
      this.ids = value;
    },

    handleCommand(command) {
      const data = command.substring(6);
      this.deletePicture(data);
    },

    // 删除照片
    deletePicture(id) {
      this.$confirm('确认删除这条记录吗?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        // 发送删除请求
        albumApi.deletePicture(id).then(response => {
          if (response.code === 200) {
            this.$notify({
              title: '成功',
              message: '删除成功',
              type: 'success',
              duration: 1500
            });
          } else if (response.code === 306) {
            this.$notify.error({
              title: '错误',
              message: '您没有操作权限，请联系管理员',
              duration: 1500
            });
          } else {
            this.$notify.error({
              title: '错误',
              message: '系统异常，请稍后再试',
              duration: 1500
            });
          }
          // 刷新列表
          this.fetchAllPicture();
          this.fetchAlbumInfo();
        })
      }).catch(() => {
        // 取消删除
      });
    }

  },
  watch: {
    /*id (val) {
      if(val) {
        this.fetchAlbumInfo();
      }
    },*/
  }
}
</script>

<style scoped>
.album-info {
  display: flex;
  margin-top: 2.25rem;
  margin-bottom: 2rem;
}
.album-cover {
  border-radius: 4px;
  width: 5rem;
  height: 5rem;
}
.album-check-cover {
  border-radius: 4px;
  width: 4rem;
  height: 4rem;
}
.album-detail {
  padding-top: 0.4rem;
  margin-left: 0.8rem;
}
.album-desc {
  font-size: 14px;
  margin-right: 0.8rem;
}
.operation {
  padding-top: 1.5rem;
  margin-left: auto;
}
.all-check {
  display: inline-flex;
  align-items: center;
  margin-right: 1rem;
}
.check-count {
  margin-left: 1rem;
  font-size: 12px;
}
.album-name {
  font-size: 1.25rem;
}
.photo-count {
  font-size: 12px;
  margin-left: 0.5rem;
}
.photo-item {
  width: 100%;
  position: relative;
  cursor: pointer;
  margin-bottom: 1rem;
}
.photo-img {
  width: 100%;
  height: 7rem;
  border-radius: 4px;
  margin-left: -3px;
}
.photo-name {
  font-size: 14px;
  margin-top: 0.3rem;
  text-align: center;
}
/*.upload-container {
  height: 800px;
}*/
.upload {
  height: 100%;
  display: flex;
  align-items: center;
  justify-content: center;
}
.upload-footer {
  display: flex;
  align-items: center;
}
.photo-opreation {
  position: absolute;
  z-index: 1000;
  top: 0.3rem;
  right: 0.5rem;
}
.album-check {
  display: flex;
  align-items: center;
}
</style>
